package com.byl.sdk.poi;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.FileURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.List;


/**
 * Created by Administrator on 2019/12/29.
 */
public class WordToHtml {
   static Logger logger= LoggerFactory.getLogger(WordToHtml.class);
   private static final String WORD_DOC="doc";
   private static final String WORD_DOCX="docx";
   public static String readDoc(HttpServletRequest request,String path,String serverurl){
       ServletContext sc = request.getSession().getServletContext();
       String root = sc.getRealPath("/").replaceAll("\\\\","/");
       System.out.println("root>>>>>>>>>>>"+root+path);
       String tmp=path.substring(0,path.lastIndexOf("/")+1);
       System.out.println("tmp========"+tmp);
       String ext=path.substring(path.lastIndexOf(".")+1);
       if(WORD_DOC.equalsIgnoreCase(ext)){
           return doc2Html(root,path,serverurl);
       }else if(WORD_DOCX.equalsIgnoreCase(ext)){
           return docx2Html(root+path);
       }
       return "";
   }

    /**
     * doc转换为html
     */
    private static String doc2Html(String root,String fileName,String serverurl)  {
        String data="";
        HWPFDocument wordDocument = null;
        String tmp=fileName.substring(0,fileName.lastIndexOf("/")+1)+System.currentTimeMillis()+"/";

        try {
            wordDocument = new HWPFDocument(new FileInputStream(root+fileName));
        } catch (IOException e) {
            logger.info("###读取doc文档失败:"+e.getMessage());
        }
        WordToHtmlConverter wordToHtmlConverter = null;
        try {
            wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        } catch (ParserConfigurationException e) {
            logger.info("###WordToHtmlConverter生成失败:"+e.getMessage());
        }
        wordToHtmlConverter.setPicturesManager(new PicturesManager() {
            public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
                return serverurl+tmp + suggestedName;
            }
        });
        wordToHtmlConverter.processDocument(wordDocument);
        // 保存图片
        List<Picture> pics = wordDocument.getPicturesTable().getAllPictures();
        if (pics != null) {
            for (int i = 0; i < pics.size(); i++) {
                Picture pic = (Picture) pics.get(i);
                File file=new File(root+tmp);
                if(!file.exists())
                    file.mkdirs();
                    try {
                        pic.writeImageContent(new FileOutputStream(root+tmp + pic.suggestFullFileName()));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }
        }
        Document htmlDocument = wordToHtmlConverter.getDocument();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(out);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = null;
        try {
            serializer = tf.newTransformer();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        }
        serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        try {
            serializer.transform(domSource, streamResult);
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        data=out.toString();
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }


    private static String docx2Html(String fileName)  {
        String data = "";
        XWPFDocument document = null;
        try {
            document = new XWPFDocument(new FileInputStream(fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        XHTMLOptions options = XHTMLOptions.create();
        // 导出图片
        File imageFolder = new File("d:/");
        options.setExtractor(new FileImageExtractor(imageFolder));
        // URI resolver
        options.URIResolver(new FileURIResolver(imageFolder));

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStream outStream = new BufferedOutputStream(baos);
        try {
            XHTMLConverter.getInstance().convert(document, outStream, options);
        } catch (IOException e) {
            e.printStackTrace();
        }
        data = baos.toString();
        try{
            if(null!=baos)
                baos.close();
            if(null!=outStream)
                outStream.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        return data;
    }

    public static void main(String []args){
      // docx2Html();
       //System.out.println(doc2Html("d:/","d:/test.doc",""));
    }
}
